from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers

from apps.users.models import User


class PermissionModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = '__all__'


class ContentTypeModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContentType
        # 看前段代码 发现只需要id和name
        fields = ['id', 'name']


# 组的序列化器
class GroupSerialzier(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = "__all__"


# 管理員 的序列化器

class AdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"

    def create(self, validated_data):
        # 重写create 给密码加密 和设置is_staff为1
        # 调用父类方法 帮助创建user对象
        user = super().create(validated_data)
        # 给密码加密
        user.set_password(validated_data.get("password"))
        # 设置is_staff为1
        user.is_staff = 1
        user.save()
        return user
